package pc.system;

import java.io.*;
import javax.servlet.http.*;
import java.util.*;
import pc.sql.*;
import pc.util.*;



public class WServlet extends HttpServlet
{
  private String db_name = null;
  private String servlet_name = null;
  //
  public HttpServletRequest request = null;
  public HttpServletResponse response = null;
  //
  private static WTimer timer = null;

  public static final int taskLogon     = 1;
  public static final int taskLogout    = 2;
  public static String window_width  = "1000";
  public static final  String defPage = "logon.jsp";
  private static Hashtable userList = new Hashtable();
  private static Hashtable connList = new Hashtable();

  //
  public WServlet(String db_name, String servlet_name)
  {
    this.db_name = db_name;
    this.servlet_name = servlet_name;
    System.out.println("00000000");
  }

  //Initialize global variables
  public void init() //throws ServletException
  {
	  System.out.println("Main Init Started");
    if (userList == null) userList = new Hashtable();
    if (connList == null) connList = new Hashtable();
    if (timer == null) {
      timer = new WTimer();
      timer.start();
    }
  }

  public String getWorkPath()
  {
    String realPath = getServletContext().getRealPath(defPage);
    return new File(realPath).getParent();
  }

  public String getMsg(Auth auth)
  {
    java.util.Date now = new java.util.Date();
    return
        this.servlet_name + " - " + Utils.dateToStr(now) + " " + Utils.timeToStr(now) +
        " -> " + auth.getUserName() + " (" + request.getRemoteAddr() + ")" ;
  }
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  {
    this.request = request;
    this.response = response;

    switch (this.getTaskID()) {
      case taskLogon:
        //doLogon();
        return;
      case taskLogout:
        doLogout();
        return;
    }

    sendRedirect(defPage);
  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  {
    doGet(request, response);
  }

  //Clean up resources
  public void destroy()
  {
    userList.clear();
    //connPool.releaseConnections();

    Enumeration e = connList.elements();

    while (e.hasMoreElements()) {
      ConnectionPool conn = (ConnectionPool)e.nextElement();
      conn.releaseConnections();
    }
    connList.clear();
    timer.terminate();
  }

  public int getTaskID()
  {
    String param = request.getParameter("taskID");
    if (param == null) {
      return -1;
    }
    return Integer.parseInt(param);
  }

  public String forwardTo(String uid,String page)
  {
		System.out.println("Working-Forward");
    PrintWriter out = null;
    try {
      out = response.getWriter();
    }  catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    String s = "<html><body>";
    s += "<form  name='formForward' id='formForward' method='post' + action='" + page + "'>";
    s += "<input type='hidden' name='uid' id='uid' value='" + uid + "'>";
    s += "</form>";
    s += "<script language='javascript'>";
    s += "document.formForward.submit()";
    s += "</script>";
    s += "</body></html>";
    out.print(s);
    return s;
 }

 public static Auth getAuth(String uid, String language, Auth new_auth)
 {
   Auth auth = null;
   if (language == null) language = "us";
   if (userList == null || uid == null) auth = new_auth;
   else auth = (Auth)userList.get(uid);
   if (auth == null) auth = new_auth;
   return auth;
 }

  public static Auth getAuth(String uid, Auth new_auth)
  {
    return getAuth(uid,null, new_auth);
  }

  public static Auth getAuth(String uid)
  {
    return getAuth(uid,null, null);
  }

  private synchronized boolean removeUser(String uid)
  {
    if (userList == null || uid == null) return false;
    return userList.remove(uid) != null;
  }

  private boolean removeUser(Auth user)
  {
    return removeUser(user.getuid());
  }

  private Auth outUser(String user_name)
  {
    if (userList == null || user_name == null) return null;
    int count = 0;
    Auth user = null;
    Enumeration e = userList.elements();
    String sid = db_name + ":" + user_name;
    while (e.hasMoreElements()) {
      Auth usr = (Auth)e.nextElement();
      if (sid.equals(usr.get_SID())) {
        if (user == null) user = usr;
        count++;
        if (count > user.getMaxLogon()) return user;
      }
    }
    return null;
  }

  private int getLogonCount(String user_name)
  {
    if (userList == null || user_name == null) return 0;
    int count = 0;
    Enumeration e = userList.elements();
    while (e.hasMoreElements()) {
      Auth usr = (Auth)e.nextElement();
      if (usr.getUserName().equals(user_name)) count++;
    }
    return count;
  }

  public void sendRedirect(String page)
  {
    try {
      this.response.sendRedirect(page);
    }    catch (IOException e) {
      e.printStackTrace();
    }
  }

  public String getParameter(String name)
  {
    if (request != null) return request.getParameter(name);
    else return null;
  }

  public static Hashtable getUserList()
  {
    return userList;
  }

  public static ConnectionPool getConnectionPool(String db_name)
  {
    ConnectionPool conn = (ConnectionPool)connList.get(db_name);
    if (conn == null) {
      conn = new ConnectionPool("localhost:3306", db_name, "root", "root");
      connList.put(db_name,conn);
      System.out.println("Create Connection Pool = " + conn.toString());
    }
    return conn;
  }

  public void putUser(Auth auth)
  {
    Auth out_usr = outUser(auth.getUserName());
    if (out_usr != null) {
      if (removeUser(out_usr)) {
        out_usr.logOut();
      }
    }
    auth.setCount(getLogonCount(auth.getUserName()));
    userList.put(auth.getuid(),auth);
  }

  public void doLogon(Auth auth)
  {
    if (auth.getUserName() == null || auth.getPassword() == null) {
      sendRedirect(defPage);
      return;
    }

    if (!auth.Authenticated()) {
      System.out.println(getMsg(auth) + " logon failed. ");
      auth.logOut();
      sendRedirect(defPage);
      return;
    }
    System.out.println(getMsg(auth) + " logon. ");
    putUser(auth);
    String linkPage = this.request.getParameter("linkPage");
    if (linkPage == null) linkPage = defPage;
	forwardTo(auth.getuid(),linkPage);
	
    //String AppType = this.request.getParameter("type");
    //if ((AppType.compareTo("A")==0)&& (auth.getUserType().compareTo("C")==0))
    //{
    	//doLogout();
    //}
    //else
    //{

    //}
  }

  public void doLogout()
  {
    String uid = this.request.getParameter("uid");
    Auth auth = getAuth(uid);
    if (auth != null) {
      System.out.println(getMsg(auth) + " logout. ");
      auth.logOut();
      removeUser(auth);
    }
    sendRedirect(defPage);
  }

}
